//
//  SettingDone.swift
//  OverRun
//
//  Created by 魔码传媒 on 2017/06/16.
//  Copyright © 2017年 magicode. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import SwiftHTTP
import HandyJSON
import AVFoundation
import AssetsLibrary
import Photos

class Settings: NSObject
{
    enum NetworkEnviron:Int
    {
        case
        UnknowNetwork,
        NoNetwork,
        ThreeGNetwork,
        WifiNetwork
    }
    
    enum ThirdUserState:Int
    {
        case
        noUser,
        localUser,
        wechatUser,
        qqUser,
        weiboUser
    }
    
    static public func getTotalCacheSize() -> Float
    {
        return 0
    }
    
    static public func needAutoLogin() -> Bool
    {
        return false
    }
    
    static public func setAutoLogin(status:Bool)
    {
        
    }
    
    static public func checkNetworkStatus() -> NetworkEnviron
    {
        return NetworkEnviron.UnknowNetwork
    }
    
//    func networkStatus() -> NetworkStatus
//    {
//        
//    }
    
    static public func checkSystemLanguage() -> String
    {
        return ""
    }
    
    static public func checkUser() -> Bool
    {
        return false
    }
    
    static public func checkThirdUserState() -> Int
    {
        return 0
    }
    
    static public func setThirdUserState(state:Int)
    {
        
    }
    
    static public func areWeEn() -> Bool
    {
        return false
    }
    
    static public func getUser() -> User
    {
        return User()
    }
    
    static public func setUserId(userId:String)
    {
        
    }
    
    static public func getUserId() -> String
    {
        return ""
    }
    
    static func getUserName() -> String
    {
        return ""
    }
    
    static func getUserInfor(userId:NSString) -> Dictionary<String, Any>
    {
        return ["random":false]
    }
    
    static func setVipEndTime(date:String)
    {
        
    }
    
    static func currentVersion() -> String
    {
        return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
    }
    
    static func savedVersion() -> String
    {
        return UserDefaults.value(forKey: "SAVED_VERSION") as! String
    }
    
    static func updateSavedVersion(version:String)
    {
        UserDefaults.setValue(version, forKey: "SAVED_VERSION")
    }
    
    static func verCompare(a:String, b:String) -> Bool
    {
        let versionA = Int(a.replacingOccurrences(of: ".", with: ""))
        let versionB = Int(b.replacingOccurrences(of: ".", with: ""))
        
        if versionA! > versionB! {
            return true
        } else {
            return false
        }
    }
    
    //跳转到应用的AppStore页页面
    static func riseAppStore(id:String)
    {
        let urlString = "itms-apps://itunes.apple.com/app/id" + id
        let url = NSURL(string: urlString)
        UIApplication.shared.openURL(url! as URL)
    }
    
    static func checkAlbAuth(result: @escaping (Bool) -> Void) -> Void
    {
        if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
            PHPhotoLibrary.requestAuthorization({
                (status: PHAuthorizationStatus) in
                    if status == PHAuthorizationStatus.authorized {
                        result(true)
                    }else
                    {
                        result(false)
                    }
            })
        }else{
            result(true)
        }
    }
    
    static func checkCamAlbAuth() -> (Bool,Bool)
    {
        // 相机权限
        let camAuthStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        let cam = camAuthStatus != .restricted && camAuthStatus != .denied && camAuthStatus != .notDetermined
    
        // 相册权限
//        let aluAuthStatus = PHAuthorizationStatus.authorizationStatus()
//        let alb = aluAuthStatus != .restricted && aluAuthStatus != .denied
        
        let authStatus = ALAssetsLibrary.authorizationStatus()
        let alb = authStatus != .restricted && authStatus != .denied && authStatus != .notDetermined
        
//        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
//        if(library == PHAuthorizationStatus.Denied || library == PHAuthorizationStatus.Restricted){
//            return false
//        }else {
         return (cam, alb)
//        }
    }
    
    static func requestCamAlbAuth()
    {
        let url = URL(string:UIApplicationOpenSettingsURLString)
        
        if(UIApplication.shared.canOpenURL(url!)){
            UIApplication.shared.openURL(url!)
        }
    }

    static func checkDevice() -> String
    {
        if(UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad)//ipad
        {
            return "ipad"
        }
        else//iphone
        {
            if UIScreen.main.bounds.height == 812 {
                return "x"
            }
            return "iphone"
        }
    }
    
    //检查是否为当前版本安装后第一次运行
    static func checkFirst() -> Bool{
        // 得到当前应用的版本号
        let currentVersion = Settings.currentVersion()
        
        // 取出之前保存的版本号
        let savedVersion = Settings.savedVersion()
        
        if Settings.verCompare(a: currentVersion, b: savedVersion){
            Settings.updateSavedVersion(version: currentVersion)
            return true
        }else{
            return false
        }
    }
    
    //作者：Hesse_Huang
    //链接：http://www.jianshu.com/p/25b008874360
    //來源：简书
    static func checkUpdateForAppID(ID: String,  handler:@escaping (_ status: Bool, _ current: String, _ new: String) -> () ) -> Void
    {
        do
        {
            let opt = try HTTP.GET("http://itunes.apple.com/lookup?id=\(ID)", parameters: nil)
            opt.start
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")
                        
                        return//also notify app of failure as needed
                    }
                    
                    let data = response.data
                    
                    let dic = try! JSONSerialization.jsonObject(with: data,
                                                                options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    let results = dic.object(forKey: "results" as Any) as! Array<Any>
                    
                    if results.count < 1{
                        return
                    }
                    
                    let storeInfo = JSONDeserializer<StoreInfors>.deserializeFrom(dict: dic)?.results?[0]
                    
                    guard
                        let version = storeInfo?.version,
                        let versionInt = Int(version.replacingOccurrences(of: ".", with: ""))
                    
                        //version.stringByReplacingOccurrencesOfString(".", withString: "")),
//                    ?(NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String),

//                        let thisVersion = (NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String),
//                        let thisVersionInt = ddInt(thisVersion.stringByReplacingOccurrencesOfString(".", withString: ""))
                        else {
                            NSLog("无法获取到App版本信息")
                            return
                        }
                    
                    let thisVersion = Settings.currentVersion()
                    let thisVersionInt = Int(thisVersion.replacingOccurrences(of: ".", with: ""))
        
                    if versionInt > thisVersionInt! {
//                    if 2 > 1 {
                        // 在下面的回调中可以做一些如弹窗等操作提示用户更新
                        handler(true, thisVersion, version)
                    } else {
                        NSLog("App已经是最新版本")
                        handler(false, thisVersion, version)
                    }
            }
        }
        catch let error
        {
            print("got an error creating the request: \(error)")
            //                callback(Result.FAILED)
        }

    }
    
    
    

}
